package com.aiobc.business.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by limengyang on 2018/10/18.
 * 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 定时任务线程池
     * @return
     */
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //线程池维护线程的最少数量-核心线程
        int corePoolSize3 = 4;
        executor.setCorePoolSize(corePoolSize3);
        //线程池维护线程的最大数量-最大线程
        int maxPoolSize3 = 64;
        executor.setMaxPoolSize(maxPoolSize3);
        //缓存队列
        int queueCapacity3 = 2048;
        executor.setQueueCapacity(queueCapacity3);
        //线程名称
        String taskThreadName3 = "AsyncTaskThread-";
        executor.setThreadNamePrefix(taskThreadName3);
        // 当线程已经达到最大的时候，不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //允许的空闲时间
        int keepAlive3 = 60;
        executor.setKeepAliveSeconds(keepAlive3);
        //是否允许核心线程空闲退出，默认值为false
        executor.setAllowCoreThreadTimeOut(true);
        // 初始化线程
        executor.initialize();
        return executor;
    }
}
